package cn.knight.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginZuulFilter extends ZuulFilter {

    // 指定filter类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    // filter执行顺序，越小越先执行
    @Override
    public int filterOrder() {
        return 0;
    }

    // 是否执行run方法
    @Override
    public boolean shouldFilter() {

        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String url = request.getRequestURI();
        if (url.endsWith("/lonin") || url.endsWith("/register") ||url.endsWith("/static/") ){
            return false;
        }

        return true;
    }

    // zuul核心方法,登录判定，token存在&正确，放行
    // false-> 没有登录，返回错误信息
    @Override
    public Object run() throws ZuulException {

        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();

        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        String token = request.getHeader("token");

        if (StringUtils.isBlank(token) && !tokenIsTrue(token)){
            Map<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("message","滚去登录");
            map.put("code",402); // 状态码

            String result = JSON.toJSONString(map);

            response.setStatus(402);

            try {
                response.getWriter().print(result);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 拦截 zuul的固定写法
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }

        // 放行
        return null;
    }


    public Boolean tokenIsTrue(String token){
        // TODO 判断token是否正确逻辑
        return false;
    }


}


